import * as api from '@/services/checkSchedule';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { Card, Checkbox, Col, Divider, Row, Space, TreeSelect, message } from 'antd';
import React, { useRef, useState } from 'react';
import * as c from '@/services/consts';
import { ProFormDateTimePicker, ProFormDependency, ProFormDigit, ProFormSelect, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import CheckServer from '@/components/CheckServer';
import { useModel } from 'umi';

type VpnServerFormProps = {
  visible: boolean;
  current?: API.CheckSchedule | undefined;
  onCancel: () => void;
  onSubmit: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, current, onCancel, onSubmit } =
    props;

  if (!visible) {
    return null;
  }

  // console.log(groupIds, groups, instIds, servers);

  const formRef = useRef<ProFormInstance>();
  // const [myloading, setMyloading] = useState<boolean>(true);
  // const [dataSource, setDataSource] = useState<API.CheckTask | undefined>(undefined,);
  // const [dataCheckers, setDataCheckers] = useState<API.CheckServer[] | undefined>(undefined);
  // const [dataTemplets, setDataTemplets] = useState<API.NodeTemplate[] | undefined>(undefined);
  // const [changeCheckedList, setChangeCheckedList] = useState<any[]>([]);
  // const [checkedTempletList, setCheckedTempletList] = useState<any[]>([]);
  // const [checkJob, setCheckJob] = useState<string|undefined>('checknode');

  const [checkedList, setCheckedList] = useState<any[]>((current?.checkServerGroups?.map((val)=>val)) ?? []);
  const [checkedType, setCheckedType] = useState<string|undefined>('group');
  const [selGroupIds, setSelGroupIds] = useState<string[] | undefined>(current?.taskGroupIds?.map((val)=>val));

  // const [checkeBlock, setCheckeBlock] = useState<boolean>(false);
  // const [groupEditableKeys, setGroupEditableKeys] = useState<React.Key[]>(() =>groupIds.map((item) => item),);
  // const [serverEditableKeys, setServerEditableKeys] = useState<React.Key[]>([]);
  // const [enableCheck, setEnableCheck] = useState<boolean>(true);
  // const [enableChangeIp, setEnableChangeIp] = useState<boolean>(true);


  
  const { getVpnGroupExTrees } = useModel('useGlobalModel', (model) => ({
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    // supplierOptions: model.supplierOptions,
  }));


  const handleFormSubmit = async (record: API.CheckSchedule) => {
    
    if(!checkedList || checkedList.length == 0){
      message.error("请选择用于检测的服务器");
      return;
    }
    // if(!job){
    //   message.error("请选择检测类型");
    //   return;
    // }
    // if(!record.taskLevel){
    //   message.error("请选择检测级别");
    //   return;
    // }

    if(checkedType == 'group'){
      record.checkServerGroups = checkedList;
      record.checkServerIds = undefined;
    }
    else{
      record.checkServerGroups = undefined;
      record.checkServerIds = checkedList;
    }

    // record.taskInstanceIds = serverEditableKeys.map((val) => val as number);
    record.taskGroupIds = selGroupIds;
    record.taskLevel = c.CheckLevel.Normal.value;
    
    console.log(record);
    console.log({ ...current, ...record });
    // return;

    let result;
    if(current){
      result = await api.update({ ...current, ...record });
    }
    else {
      result = await api.create({ ...record });
    }

    if (result && result.success) {
      onSubmit();
    }

  };

  const handleSetChecked = (values: any[], valueType: string) => {
    setCheckedList(values);
    setCheckedType(valueType);
  }
  


  return (
    <DrawerForm<API.CheckSchedule>
      open={visible}
      title={`${current ? '编辑' : '添加'}自动任务`}
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      initialValues={current}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
    >

      <Row gutter={24}>
        <Col span={12}>
          <ProFormText
            name="name"
            label="名称"
            rules={[{ required: true, message: '请输入名称' }]}
          />
        </Col>
        <Col span={3}>
          <ProFormDigit
            name="interval"
            label="运行间隔(分钟)"
            min={1}
            max={1000}
            fieldProps={{ precision: 0 }}
            rules={[{ required: true, message: '请输入自动运行间隔' }]}
            allowClear={false}
          />
        </Col>
        <Col span={3}>
          <ProFormSwitch
            name={['policy', 'runEndStartTiming']}
            label="运行完后计时"
            initialValue={true}
          />
        </Col>
        <Col span={4}>
          <ProFormDateTimePicker
            name="startTime"
            label="开始时间"
          />
        </Col>
        <Col span={2}>
          <ProFormSwitch
            name="status"
            label="状态"
            initialValue={true}
          />
        </Col>
      </Row>


      <Card style={{ marginTop: 10, padding: 0 }} title='检测服务器'>
        <Row gutter={24}>
          <Col span={4}>
            <ProFormDigit
              name={['policy', 'checkPolicy', 'checkServerCount']}
              label="每组下发数"
              min={1}
              max={10}
              allowClear={true}
              rules={[{ required: true, message: '请输入每组同时下发检测数' }]}
            />
          </Col>
          <Col span={4}>
            <ProFormDigit
              name={['policy', 'checkPolicy', 'virtualCheckServerCount']}
              label="Virtual每组下发数"
              min={0}
              max={100}
              allowClear={true}
            />
          </Col>
        </Row>
        <CheckServer onChange={handleSetChecked} width={1100} displayType={checkedType} showDisplayType={false} initValues={checkedList} />
      </Card>
                 

      <Card style={{ marginTop: 30, padding: 0 }} title={
          <Row gutter={24} style={{marginTop:10,marginBottom:-10}}>
            <Col span={1}>
              <ProFormSwitch
                name={['policy', 'checkPolicy', 'status']}
                label=""
                fieldProps={{
                  defaultChecked: true,
                }}
                initialValue={true}
              />
            </Col>
            <Col span={8} style={{paddingTop:5}}>自动检测</Col>
          </Row>
        }>
        <ProFormDependency name={['policy', 'checkPolicy', 'status']}>
          {(val) => {
            // console.log(val.policy);
            if (val?.policy?.checkPolicy?.status == true) {
              return (<>
                <Row gutter={24} style={{marginTop:10}}>
                  {/* <Col span={4}>
                    <ProFormSelect
                      name='taskLevel'
                      label="任务等级"
                      allowClear={false}
                      options={c.CheckLevelOptions}
                      mode='single'
                      initialValue={c.CheckLevel.Normal.value}
                      // rules={[{ required: true, message: '请选择任务等级' }]}
                    />
                  </Col> */}
                  <Col span={4}>
                    <ProFormSelect
                      name='taskJob'
                      label="检测类型"
                      allowClear={false}
                      options={c.CheckJobAutoOptions}
                      mode='single'
                      initialValue={c.CheckJob.HttpPost.value}
                      fieldProps={{
                        listHeight:600
                      }}
                      rules={[{ required: true, message: '请选择检测类型' }]}
                    />
                  </Col>
                  {/* <ProFormDependency name={['taskJob']}>
                    {({ job }) => {
                      if (job == c.CheckJob.CheckNode.value) {
                        return (
                        <Col span={4}>
                          <ProFormSelect
                            name='mode'
                            label="检测模式"
                            allowClear={false}
                            options={c.CheckModeOptions}
                            mode='single'
                            initialValue={c.CheckMode.Simple.value}
                            fieldProps={{
                              listHeight:600
                            }}
                          />
                        </Col>
                        );
                      }
                      return null;
                    }}
                  </ProFormDependency> */}
                  <Col span={4}>
                    <ProFormSelect
                      name='taskCheckStatus'
                      label="检测项状态"
                      allowClear={false}
                      options={c.CheckTaskItemStatusOptions}
                      mode='single'
                      initialValue={-1}
                    />
                  </Col>
                  <Col span={3}>
                    <ProFormSwitch
                      name='taskCheckBlock'
                      label="检测被墙"
                      fieldProps={{
                        defaultChecked: false,
                      }}
                      initialValue={false}
                    />
                  </Col>
                  <Col span={4}>
                    <ProFormDigit
                      name={['policy', 'checkPolicy', 'instanceCount']}
                      label="一次检测最多服务器数"
                      min={0}
                      max={10000}
                      allowClear={true}
                    />
                  </Col>
                  <Col span={4}>
                    <ProFormSwitch
                      name={['policy', 'checkPolicy', 'blockForSecondCheck']}
                      label="初检被墙进行二检"
                      fieldProps={{
                        defaultChecked: true,
                      }}
                      initialValue={true}
                    />
                  </Col>
                </Row>

                {/* <Row gutter={24} style={{marginTop:10}}>
                  <Col span={4}>
                    <ProFormDigit
                      name={['policy', 'checkPolicy', 'instanceCount']}
                      label="一次最多检测服务器数"
                      min={0}
                      max={10000}
                      allowClear={true}
                    />
                  </Col>
                  <Col span={4}>
                    <ProFormDigit
                      name={['policy', 'checkPolicy', 'serverBlockedCount']}
                      label="结果中几个被墙视为被墙"
                      min={0}
                      max={100}
                      allowClear={true}
                    />
                  </Col>
                </Row> */}

                <ProFormDependency name={['taskJob']}>
                {(val) => {
                  // console.log(val);
                  if (val.taskJob == c.CheckJob.HttpPost.value) {
                    return (<>
                      <Divider orientation="left" orientationMargin={0} style={{marginTop:0}}>检测分组</Divider>
                      <Row gutter={24}>
                        <Col span={24}>
                          <TreeSelect
                            style={{ minWidth: '100%', marginTop: 0, marginBottom: 0 }}
                            listHeight={600}
                            // maxTagCount={1}
                            // dropdownMatchSelectWidth={false}
                            placeholder="选择分组"
                            allowClear={true}
                            showSearch={true}
                            treeCheckable={true}
                            // multiple={false}
                            treeDefaultExpandAll
                            treeData={getVpnGroupExTrees(undefined, true)}
                            value={selGroupIds}
                            treeNodeFilterProp="title"
                            onChange={(value) => {
                              setSelGroupIds(value ? value : undefined);
                            }}
                          />
                        </Col>
                      </Row>
                    </>);
                  }
                  else if (val.taskJob){
                    return (<>
                      <Row gutter={24}>
                        <Col span={24}>
                          <ProFormTextArea name="taskCustoms" 
                            label="检测内容" 
                            fieldProps={{rows:10}} 
                            rules={[{ required: true, message: '请输入检测内容' }]}
                          />
                        </Col>
                      </Row>
                    </>);
                  }
                  return null;
                }}
                </ProFormDependency>

                    </>);
            }
            return null;
          }}
        </ProFormDependency>
      </Card>

      
      <Card style={{ marginTop: 30, padding: 0 }} title={
          <Row gutter={24} style={{marginTop:10,marginBottom:-10}}><Col span={1}><ProFormSwitch
            name={['policy', 'changeIpPolicy', 'status']}
            label=""
            fieldProps={{
              defaultChecked: true,
            }}
            initialValue={true}
          /></Col><Col span={8} style={{paddingTop:5}}>自动更换IP</Col></Row>
        }>
        <ProFormDependency name={['policy', 'changeIpPolicy', 'status']}>
          {(val) => {
            // console.log(val.policy);
            if (val?.policy?.changeIpPolicy?.status == true) {
              return (<>
                <Row gutter={24} style={{marginTop:10}}>
                  <Col span={4}>
                    <ProFormDigit
                      name={['policy', 'changeIpPolicy', 'maxTimes']}
                      label="最多更换次数"
                      min={0}
                      max={100}
                      allowClear={true}
                    />
                  </Col>
                  {/* <Col span={4}>
                    <ProFormDigit
                      name={['policy', 'changeIpPolicy', 'minBlockedTimes']}
                      label="检测几次被墙后开始更换"
                      min={0}
                      max={100}
                      allowClear={true}
                    />
                  </Col> */}
                  <Col span={3}>
                    <ProFormSwitch
                      name={['policy', 'changeIpPolicy', 'checkIpBlacklist']}
                      label="比对黑名单"
                      fieldProps={{
                        defaultChecked: true,
                        // onChange:(checked) =>{
                        //   // console.log(formRef.current?.getFieldValue(['policy', 'changeIpPolicy', 'endRecheck']));
                        //   if(checked == true){
                        //     formRef.current?.setFieldValue(['policy', 'changeIpPolicy', 'endRecheck'], false);
                        //   }
                        // }
                      }}
                      initialValue={true}
                    />
                  </Col>
                  <Col span={3}>
                    <ProFormSwitch
                      name={['policy', 'changeIpPolicy', 'endRecheck']}
                      label="更换后重新检测"
                      fieldProps={{
                        defaultChecked: false,
                        // onChange:(checked) =>{
                        //   if(checked == true){
                        //     formRef.current?.setFieldValue(['policy', 'changeIpPolicy', 'checkIpBlacklist'], false);
                        //   }
                        // }
                      }}
                      initialValue={false}
                    />
                  </Col>
                </Row>
              </>);
            }
            return null;
          }}
        </ProFormDependency>        
      </Card>
      




    </DrawerForm>
  );
};

export default VpnServerForm;
